package Scuttlebutt;

import glue.ftp.*;
import java.awt.Component;
import java.awt.event.*;
import java.awt.Rectangle;
import java.awt.CardLayout;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Insets;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.SpringLayout;
import javax.swing.table.AbstractTableModel;
import javax.swing.*;
import java.io.*;
import java.util.*;

public class SynchronizeDlg extends JDialog// implements FtpObserver 
{
    private boolean DEBUG = false;
	Scuttlebutt parent = null;
	JLabel name = null; 
//	long num_of_bytes = 0;  
	SelectPanel sp = null;
	SynchronizePanel syncp = null;
	CardLayout cl = null;
	
//	JProgressBar bar = null;
	
    final static String SelectPanelText = "Select Directories:";
    final static String SynchronizePanelText = "Synchronize";

	DownloadButtonAction DownloadAction = null;
	CancelButtonAction cancelAction = null;
	
	JButton Download = null;
	JButton cancel = null;
	
	JPanel cards = null;

    class MyTableModel extends AbstractTableModel {
	    SynchronizeDlg dlg = null;
		ArrayList<rowData> selected = null;
        private String[] columnNames = {"download","folder"};
	        
	    public MyTableModel(SynchronizeDlg dlg){
		    this.dlg = dlg;
		    selected = new ArrayList<rowData>();
			getFiles(FtpListResult.DIRECTORY);
			getFiles(FtpListResult.FILE);
	    }
	    
	    public int getColumnCount(){
		    return 2;
	    }
	    
	    public int getRowCount(){
		    return selected.size();
	    }
	    
        public String getColumnName(int col) {
            return columnNames[col];
        }
	    
       	public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
	    
	    public Object getValueAt(int row, int col){
		    return(col == 0)?((rowData)selected.get(row)).select : ((rowData)selected.get(row)).path;
	    }
	    
	    public rowData getValueAt(int row){
		    return (rowData)selected.get(row);
	    }
	    
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            if (col > 0) {
                return false;
            } else {
                return true;
            }
        }
        
        public void setValueAt(Object value, int row, int col) {
            if (DEBUG) {
                System.out.println("Setting value at " + row + "," + col
                                   + " to " + value
                                   + " (an instance of "
                                   + value.getClass() + ")");
            }

            rowData data = getValueAt(row);
            rowData d = new rowData(data);

            if(col == 0){
	 			d.select = (Boolean)value;
 			}else{
	 			d.path = value.toString();
 			}
 			
 			selected.set(row, d);

            fireTableCellUpdated(row, col);

            if (DEBUG) {
                System.out.println("New value of data:");
//                printDebugData();
            }
        }
        
        
	    
		private void getFiles(int type){
			try{
				FtpListResult result = dlg.parent.getFTP().getDirectoryContent();
		        while(result.next()){
		            int test = result.getType();
		            if(test == type){
			            rowData data = new rowData(new Boolean(false), result.getName());
			            selected.add(data);
		            }
		        }
		    } catch(Exception e){
	//	        System.err.println("num:" + num + " *Thread error:" + e);
		    }
		}
    }
    
    public class rowData extends Object{
	    public Boolean select;
	    public String path = null;
	    public rowData(Boolean select, String path){
		    this.select = select;
		    this.path = path;
	    }
	    
	    public rowData(rowData a){
		    this.select = a.select;
		    this.path = a.path;
	    }
	    
	    public String toString(){
		    String msg = new String("select:" + select + " path:" + path);
		    return msg;
	    }
    }
    
	public class SelectPanel extends JPanel{
		SynchronizeDlg dlg = null;
		private JTable table = null;
		public SelectPanel(SynchronizeDlg dlg){
			this.dlg = dlg;
			init();
		}
		
		public Boolean getSelected(int row){
			return (Boolean)((MyTableModel)table.getModel()).getValueAt(row, 0);
		}
		
		public JTable getTable(){
			return table;
		}
				
		
		public void init(){
			SpringLayout layout = new SpringLayout();
			setLayout(layout);
			JLabel label = new JLabel(SelectPanelText);
			add(label);
			//Adjust constraints for the label so it's at (5,5).
			layout.putConstraint(SpringLayout.WEST, label,
			                     5,
			                     SpringLayout.WEST, getContentPane());
			layout.putConstraint(SpringLayout.NORTH, label,
			                     5,
			                     SpringLayout.NORTH, getContentPane());
			

	        table = new JTable(new MyTableModel(dlg)); 
	        table.setPreferredScrollableViewportSize(new Dimension(450, 70));
			
	        //Create the scroll pane and add the table to it.
	        JScrollPane scrollPane = new JScrollPane(table);
	
	        //Add the scroll pane to this panel.
	        add(scrollPane);
			layout.putConstraint(SpringLayout.WEST, scrollPane,
			                     5,
			                     SpringLayout.WEST, getContentPane());
			layout.putConstraint(SpringLayout.NORTH, scrollPane,
			                     25,
			                     SpringLayout.NORTH, getContentPane());
		}
		
    	private void initColumnSizes(JTable table) {
	    	javax.swing.table.TableColumn download = table.getColumnModel().getColumn(0);
	    	javax.swing.table.TableColumn path = table.getColumnModel().getColumn(1);
	    	download.setPreferredWidth(55); 
	    	path.setPreferredWidth(150);
   		}
		
		
	}
	
	public class SynchronizePanel extends JPanel implements FtpObserver {
		long num_of_bytes = 0;  
		JProgressBar bar = null;
		JList list = null;
		javax.swing.DefaultListModel model = null;
		public SynchronizePanel(){
			model = new javax.swing.DefaultListModel();
			init();
		}
		public void init(){
//			Container container=getContentPane();
//			container.setLayout(new BorderLayout());
			JPanel container = new JPanel(new BorderLayout());


			bar = new JProgressBar(0, 500);
			
			JPanel pane = new JPanel(new FlowLayout());
			JLabel label = new JLabel(SynchronizePanelText);
			pane.add(label);
			pane.add(bar);
			
			container.add(pane, BorderLayout.NORTH);
			add(container);
			list = new JList(model);
			add(new JScrollPane(list));
			
			
		}
		public void byteRead(int i0)
		{
			num_of_bytes += i0;
			bar.setValue((int)num_of_bytes);
		}
	
		public void byteWrite(int i0)
		{
		}
		
		public void SetText(String text){
			System.out.println(text);
			model.addElement(text);
			list.ensureIndexIsVisible(model.size() - 1);
		}	
	}
	
	public class DownloadButtonAction extends AbstractAction {
		SynchronizeDlg dlg = null;
		Scuttlebutt parent = null;
		SynchronizeThread thread = null;
       	public DownloadButtonAction(String text, Integer mnemonic, Scuttlebutt parent, SynchronizeDlg dlg) {
            super(text, null);
            putValue(MNEMONIC_KEY, mnemonic);
            this.dlg = dlg;
            this.parent = parent;
        }
        public void actionPerformed(ActionEvent e) {
	        dlg.Download.enable(false);
	        dlg.cancel.enable(false);
	        dlg.cl.show(dlg.cards, dlg.SynchronizePanelText);
	        Synchronize();
//	        setVisible(false);
        }
        
	 	public void Synchronize(){
		 	thread = new SynchronizeThread(parent, dlg);
			new Thread(thread).start();
		}    
	}	
	
	
	public class CancelButtonAction extends AbstractAction {
		SynchronizeDlg dlg = null;
		
        public CancelButtonAction(String text, Integer mnemonic, SynchronizeDlg dlg) {
            super(text, null);
            putValue(MNEMONIC_KEY, mnemonic);
            this.dlg = dlg;
        }
        public void actionPerformed(ActionEvent e) {
	        setVisible(false);
        }
    }	
	
	public SynchronizeDlg(Scuttlebutt parent, String title)
	{
		super(parent, title, true);
		this.parent = parent;
		setModal(true);
		setSize(500,200);
		init();
		setLocationRelativeTo(parent);
//		Synchronize();
	}
	
	private void init(){
		DownloadAction = new DownloadButtonAction("Download",new Integer(KeyEvent.VK_D),parent, this);
		cancelAction = new CancelButtonAction("Cancel",new Integer(KeyEvent.VK_C), this);
		Container container=getContentPane();
		container.setLayout(new BorderLayout());
		cl = new CardLayout();
		sp = new SelectPanel(this);
		syncp = new SynchronizePanel();
		cards = new JPanel(cl);
		cards.add(sp, SelectPanelText);
		cards.add(syncp, SynchronizePanelText);
		container.add(cards, BorderLayout.CENTER);
		
		JPanel pane = new JPanel(new FlowLayout());
		Download = new JButton(DownloadAction);
		pane.add(Download);
		cancel = new JButton(cancelAction);
		pane.add(cancel);
		container.add(pane,BorderLayout.SOUTH);
//		cl.show(sp, SelectPanelText);
	}

/*	private void init(){
		Container container=getContentPane();
		container.setLayout(null);
		setupDialog(container);
	}
*/	
/*	public void setupDialog(Container pane){
		Insets insets = pane.getInsets();
		int headspace = 5;
		int between = 5;
		int left_margin = 20;
		
		name = new JLabel("Path:");
		pane.add(name);
		Dimension size = name.getPreferredSize();
		name.setBounds(insets.left + left_margin, insets.top + headspace, size.width, size.height);

		headspace += size.height + 5;
		bar = new JProgressBar(0, 500);
		pane.add(bar);
		size = bar.getPreferredSize();
		bar.setBounds(insets.left + left_margin, insets.top + headspace, size.width, name.getPreferredSize().height);
	}
*/
/*	public void SetText(String text){
		Container pane = getContentPane();		
		Insets insets = pane.getInsets();
		name.setText(text);
		Dimension size = name.getPreferredSize();

		Rectangle bounds = name.getBounds(null);
		int left_margin = 20;
		int headspace = 5;
		name.setBounds(insets.left + left_margin, insets.top + headspace, (int)size.getWidth(), (int)bounds.getHeight());
	}
*/	
/* 	public void Synchronize(){
	 	thread = new SynchronizeThread(parent, this);
		new Thread(thread).start();
	}*/
	
/*	public void byteRead(int i0)
	{
		num_of_bytes += i0;
		bar.setValue((int)num_of_bytes);
	}

	public void byteWrite(int i0)
	{
	}*/
}

